<template>
  <div class="cartview">
    <CartTable>
      <template v-for="(cart, index) in carts" :key="index">
	<CartItem
	  :goodsid="cart.goodsid"
	  :count="cart.goodsCount"
	  :result="cart.price"
	  @delete-cart="deleteCartAt(index as number)" />
      </template>

      <template #footer>
	<tr>
	  <td colspan="4"/>
	  <td class="result">
	    合计 {{totalPrice.toFixed(2)}} 元
	  </td>

	  <td class="settlement">
	    <button @click="toggleSettle"> 结算 </button>
	  </td>
	</tr>

	<Drawer title="结算订单" v-model="showSettlement" direction="bottom-top">
	  <h2> 合计 {{totalPrice.toFixed(2)}} 元 </h2>
	  <template #footer>
	    <button @click="submitOrder"> 提交订单 </button>
	  </template>
	</Drawer>

      </template>
    </CartTable>
  </div>
</template>

<script lang="ts" setup>
 import {ref, onMounted, computed} from 'vue'
 import {CartTable, CartItem} from '@/components/Cart'
 import {findMatchCarts, currentUser, insertOrder, deleteCart} from '@/service'
 import Drawer from '@/components/Drawer.vue'

 const carts = ref<CartItem[]>([])
 const showSettlement = ref(false)
 const totalPrice = computed(() => {
   return carts.value.map(cart => cart.price).reduce((a, b) => a + b, 0)
 })

 function toggleSettle() {
   showSettlement.value = true
 }

 async function submitOrder() {
   showSettlement.value = false
   let {data} = await findMatchCarts(await currentUser())
   let cartItems = data as CartItem []
   let orderItems = cartItems.map((item: CartItem) => {
     return {
       goodsid: item.goodsid,
       goodsCount: item.goodsCount
     }
   })
   
   let order: Order = {
     userid: await currentUser(),
     price: totalPrice.value,
     items: orderItems,
     paid: false
   }

   await insertOrder(order)

   // now delete the items from cart
   for(let item of cartItems) {
     await deleteCart(item.id!)
   }

   carts.value = []

 }

 async function deleteCartAt(index: number) {
   let id = carts.value[index].id
   await deleteCart(id!)
   carts.value.splice(index, 1)
 }

 onMounted(async () => {
   let {data} = await findMatchCarts(await currentUser())
   carts.value = data
 })

</script>